package com.caiyifan.dao.impl;

import com.caiyifan.dao.UserDao;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;
import vo.User;

import javax.annotation.Resource;
import java.sql.ResultSet;
import java.sql.SQLException;
//import java.util.Collection;
import java.util.List;

@Component
public class UserDaoImpl implements UserDao {

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Override
    public User getUserByUserName(String username) {

        String sql = "select username, password from users where username = ?  ";

        List<User> userList = jdbcTemplate.query(sql, new String[]{username}, new RowMapper<User>(

        ) {
            public User mapRow(ResultSet resultSet, int i) throws SQLException {
                User user = new User();
                user.setUsername(resultSet.getString("username"));
                user.setPassword(resultSet.getString("password"));

                return user;
            }
        });

        if(CollectionUtils.isEmpty(userList)){
            return null;
        }


        return userList.get(0);
    }

    @Override
    public List<String> getRolesByUserName(String username) {

        String sql = "select role_name from user_roles where username = ?";

        return  jdbcTemplate.query(sql, new String[]{username}, new RowMapper<String>() {

            @Override
            public String mapRow(ResultSet resultSet, int i) throws SQLException {
                return resultSet.getString("row_name");
            }
        });
    }
}
